package com.ruoyi.xqsp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.*;
import com.ruoyi.xqsp.domain.entity.UserLike;
import com.ruoyi.xqsp.domain.entity.VideoSort;
import com.ruoyi.xqsp.service.ISpActorMessageService;
import com.ruoyi.xqsp.service.ISpCollectService;
import com.ruoyi.xqsp.service.ISpVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xqsp.service.ISpActorService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 演员管理Controller
 *
 * @author ruoyi
 * @date 2021-04-17
 */
@Api(value = "演员管理",tags = "演员管理")
@RestController
@RequestMapping("/xqsp/actor")
public class SpActorController extends BaseController
{
    @Autowired
    private ISpActorService spActorService;
    @Autowired
    private ISpCollectService spCollectService;
    @Autowired
    private ISpVideoService spVideoService;
    @Autowired
    private ISpActorMessageService spActorMessageService;

    /**
     * 查询演员管理列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpActor spActor)
    {
        startPage();
        List<SpActor> list = spActorService.selectSpActorList(spActor);
        return getDataTable(list);
    }

    /**
     * 查询演员管理列表
     */
    @ApiOperation("演员排序  返回参数videoWatchNumber 为播放次数")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer" ,name = "pageNum",value = "页码",required = true),
            @ApiImplicitParam(dataType = "Integer" ,name = "pageSize",value = "页面大小",required = true),
            @ApiImplicitParam(dataType = "Integer" ,name = "type",value = "类型1: 默认排序 2:播放量最高",required = true),
    })
    @GetMapping("/getAllList")
    public ResponseUtil getAllList(Integer pageNum, Integer pageSize, Integer type)
    {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<SpActor> wrapper = new QueryWrapper();

        switch (type){
            case 1:
                wrapper.orderByDesc("IF(is_top =1 ,0,1),create_time");
                break;
            case 2:
                wrapper.orderByDesc("create_time");
                break;
        }

        List<SpActor> list = spActorService.list(wrapper);
        for (SpActor actor:list
             ) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select("IFNULL(SUM(video_watch_number),0) as num");
            queryWrapper.eq("actor_id",actor.getActorId());
            Map<String,Object> map = spVideoService.getMap(queryWrapper);
            actor.setVideoWatchNumber(Integer.valueOf(map.get("num").toString()));
        }
        PageInfo<SpActor> spActorPageInfo = new PageInfo<>(list);

        return ResponseUtil.success(spActorPageInfo);
    }




    /**
     * 导出演员管理列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:export')")
    @Log(title = "演员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpActor spActor)
    {
        List<SpActor> list = spActorService.selectSpActorList(spActor);
        ExcelUtil<SpActor> util = new ExcelUtil<SpActor>(SpActor.class);
        return util.exportExcel(list, "actor");
    }

    /**
     * 获取演员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:query')")
    @GetMapping(value = "/{actorId}")
    public AjaxResult getInfo(@PathVariable("actorId") Long actorId)
    {
        return AjaxResult.success(spActorService.selectSpActorById(actorId));
    }

    /**
     * 新增演员管理
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:add')")
    @Log(title = "演员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpActor spActor)
    {
        spActorService.insertSpActor(spActor);
        return AjaxResult.success(spActor.getActorId());
    }

    /**
     * 修改演员管理
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:edit')")
    @Log(title = "演员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpActor spActor)
    {
        return toAjax(spActorService.updateSpActor(spActor));
    }

    /**
     * 删除演员管理
     */
    @PreAuthorize("@ss.hasPermi('xqsp:actor:remove')")
    @Log(title = "演员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{actorIds}")
    public AjaxResult remove(@PathVariable Long[] actorIds)
    {
        List<SpActorMessage>actorMessageList=new ArrayList<>();
        SpActorMessage spActorMessage;
        for (Long actorId : actorIds){
            spActorMessage=new SpActorMessage();
            spActorMessage = spActorMessageService.selectSpActorMessageByActorId(actorId);
            if (spActorMessage!=null){
                actorMessageList.add(spActorMessage);
            }
        }
        if (actorMessageList.size()==0){
            Long type=4l;
            for (Long actorId : actorIds){
                spCollectService.deleteSpCollect1(actorId,type);
            }

            return toAjax(spActorService.deleteSpActorByIds(actorIds));
        }else {
            return AjaxResult.error("该演员存在演员信息无法删除");
        }


    }



    /**
     * 演员收藏
     * @return
     */
    @ApiOperation("演员收藏")
    @PostMapping("/actorCollect")
    public ResponseUtil actorCollect(UserLike userLike){
        SpCollect spCollect=new SpCollect();
        spCollect.setUserId(userLike.getUserId());
        spCollect.setCollectTypeId(userLike.getActorId());
        spCollect.setCollectType(4l);
        spCollect.setCollectTime(new Date());
        if (spCollectService.selectSpCollectList(spCollect).size()==0){

            return ResponseUtil.update(spCollectService.insertSpCollect(spCollect));
        }else {

            return ResponseUtil.update(spCollectService.deleteSpCollect(spCollect));
        }
    }

    /**
     * 排序
     * @param actorId
     * @return
     */
    @ApiOperation("演员视频排序")
    @PostMapping("/getSort")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer" ,name = "pageNum",value = "页码",required = true),
            @ApiImplicitParam(dataType = "Integer" ,name = "pageSize",value = "页面大小",required = true),
            @ApiImplicitParam(dataType = "Integer" ,name = "type",value = "类型1: 默认排序 2:播放量最高 3：最近更新" ,required = true),
            @ApiImplicitParam(dataType = "Long" ,name = "actorId",value = "演员id" ,required = true),
    })
    public ResponseUtil getSort(Integer pageNum, Integer pageSize, Integer type,Long actorId){

//        startPages(videoSort.getPageNums(),videoSort.getPageSize());
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<SpVideo> wrapper = new QueryWrapper();
        wrapper.eq("actor_id",actorId);
        List<SpVideo> list = new ArrayList<>();
        wrapper.select("\tvideo_id,\n" +
                "\tvideo_name,\n" +
                "\tvideo_cover_img,\n" +
                "\tactor_id,\n" +
                "\tvideo_introduce,\n" +
                "\tvideo_watch_number,\n" +
                "\tvideo_like_number,\n" +
                "\tvideo_unlock,\n" +
                "\tvideo_category_id,\n" +
                "\tvideo_putaway,\n" +
                "\tvideo_definition,\n" +
                "\tvideo_unlock_glod,\n" +
                "\tvideo_time,\n" +
                "\tvideo_url,\n" +
                "\tvideo_unlike_number,\n" +
                "\tvideo_collect_number,\n" +
                "\tvideo_author,\n" +
                "\tvideo_type,\n" +
                "\tvideo_url_preview,\n" +
                "\tvideo_duration,\n" +
                "\tis_top,\n" +
                "\tis_top_date,\n" +
                "\tunlock_count ,\n" +
                "\tCASE WHEN ROUND(video_like_number /(video_like_number + video_unlike_number),4) = 1\n" +
                "\tTHEN IF(video_unlike_number >0,99.99,100.00)\n" +
                "\tWHEN ROUND(video_like_number /(video_like_number + video_unlike_number),4) = 0 \n" +
                "\tTHEN  IF(video_like_number >0,0.01,0.00)\n" +
                "\tWHEN video_unlike_number = 0 and video_like_number = 0\n" +
                "\tTHEN 100.00\n" +
                "\tELSE\n" +
                "\t\t\tROUND(video_like_number /(video_like_number + video_unlike_number),4) * 100\n" +
                "\tEND  as video_score");
        switch (type){
            case 1:
                wrapper.orderByDesc("IF(is_top =1 ,0,1),video_time");
                list = spVideoService.list(wrapper);
                break;
            case 2:
                wrapper.orderByDesc("video_watch_number");
                list = spVideoService.list(wrapper);
                break;
            case 3:
                wrapper.orderByDesc("video_time");
                list = spVideoService.list(wrapper);
                break;
        }

        return ResponseUtil.success(PageInfo.of(list));

    }
}
